package com.tbit.uqbike.client.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tbit.common.constant.BusinessConstant;
import com.tbit.common.constant.PayPlatformContent;
import com.tbit.common.constant.TransationLogConstant;
import com.tbit.uqbike.client.constant.*;
import com.tbit.uqbike.client.constant.enums.ControlWay;
import com.tbit.uqbike.client.dao.core.MachineBorrowDao;
import com.tbit.uqbike.client.dao.core.WeixinConfigDao;
import com.tbit.uqbike.client.dao.log.OrderLogDao;
import com.tbit.uqbike.client.dao.log.RefundOrderDao;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.*;
import com.tbit.uqbike.client.pojo.newEntity.CallbackDataVo;
import com.tbit.uqbike.client.pojo.newEntity.PayCallbackData;
import com.tbit.uqbike.client.remote.*;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Author: chen
 * @Description:
 * @Date: 创建于 11:22 2020/9/24
 */
@Service
@Slf4j
public class PayPointServiceImpl implements PayPointService {
    @Autowired
    private WeixinConfigDao weixinConfigDao;

    @Autowired
    private WeixinPayConfigService weixinPayConfigService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RechargeService rechargeService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserWxzffService userWxzffService;
    @Autowired
    private MachineBorrowDao machineBorrowDao;
    @Autowired
    private RideLogService rideLogService;
    @Autowired
    private UserAccountLogService userAccountLogService;
    @Autowired
    private TerControlService terControlService;
    @Autowired
    private OrderLogDao orderLogDao;
    @Autowired
    private MachineService machineService;
    @Autowired
    private AdAccountFeeService adAccountFeeService;
    @Autowired
    private AdaPayService adaPayService;
    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private MpBrandConfigService mpBrandConfigService;
    @Autowired
    private RefundOrderDao refundOrderDao;
    @Autowired
    private MQProducer mqProducer;

    @Override
    public SortedMap<Object, Object> leadData(Integer accountId, Integer userId) {
        WeixinConfig weixinConfig = weixinConfigDao.getByAccountId(accountId);
        if (weixinConfig == null) {
            throw new BaseException("-2006", "该品牌微信支付未配置");
        }

        WeixinPayConfig weixinPayConfig = weixinPayConfigService.getByAccountId(accountId, 2);
        if (weixinPayConfig == null) {
            throw new BaseException("-2006", "该品牌微信支付未配置");
        }
        //String orderNO = RandomOrder.GetRandom();
        String orderNO = "WXZFF" + DateTimeUtil.getDaformatyyyyMMddHHmmss(new Date()) + TenpayUtil
                .buildRandom(6);
        SortedMap<Object, Object> tree = new TreeMap<>();
        tree.put("mch_id", weixinPayConfig.getPartner());
        tree.put("service_id", weixinConfig.getServiceId());
        tree.put("out_request_no", orderNO);
        Object timestamp = System.currentTimeMillis();
        tree.put("timestamp", timestamp.toString());
        tree.put("nonce_str", RandomNumber.getRandomString(32));
        tree.put("sign_type", "HMAC-SHA256");
        String sign = HMACSHA256.sha256_HMAC(tree, weixinPayConfig.getPartnerkey());
        tree.put("sign", sign);

        /**存放redis*/
        redisService.add(RedisConstant.WXPAY_KEY_ZFF + orderNO, userId.toString(), 120);
        //log.info("跳转支付分授权页面返回值："+tree.toString());
        return tree;
    }

    @Override
    public String pre_authorization(Integer accountId, Integer userId) {
        WeixinConfig weixinConfig = weixinConfigDao.getByAccountId(accountId);
        if (weixinConfig == null) {
            throw new BaseException("-2006", "该品牌微信支付未配置");
        }

        WeixinPayConfig weixinPayConfig = weixinPayConfigService.getByAccountId(accountId, 2);
        if (weixinPayConfig == null) {
            throw new BaseException("-2006", "该品牌微信支付未配置");
        }
        /**兼容预授权骑行过程中不许在授权*/
   /* MachineBorrow machineBorrow= machineBorrowDao.getByUserId(userId);
    if(machineBorrow!=null){
      throw new BaseException("-3005","目前您还有骑行中订单，请结束订单后再操作");
    }*/
        Recharge recharge = rechargeService.getByWxzzfNotPay(userId, RechargeConstant.RECHARGE_WEIXIN_AFF);
        if (recharge != null) {
            throw new BaseException("-170001", "存在未结束支付分订单");
        }
        String orderNO = "AUTH" + DateTimeUtil.getDaformatyyyyMMddHHmmss(new Date()) + TenpayUtil
                .buildRandom(6);
        JSONObject parameters = new JSONObject();
        parameters.put("authorization_code", orderNO);//商户系统内部授权协议号，要求此参数只能由数字、大小写字母_-*组成，且在同一个商户号下唯一
        parameters.put("appid", weixinPayConfig.getAppId());//公众账号ID
        parameters.put("service_id", weixinConfig.getServiceId());//服务ID
        parameters.put("notify_url", weixinConfig.getCallbackURL());//商户接收授权回调通知的地址

        JSONObject workOrder;
        String url = "https://api.mch.weixin.qq.com/v3/payscore/permissions";
        log.info("创建预授权传递值:   " + parameters);
        String data;
        try {
            data = HttpRequest.post(url)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.ACCEPT, "application/json")
                    // 签名
                    .header("Authorization", "WECHATPAY2-SHA256-RSA2048" + " "
                            + PayScore
                            .getToken("POST", url, JSONObject.toJSONString(parameters), weixinPayConfig.getPartner(), weixinConfig.getCertSerNo(), String.format(
                                    WeixinConstant.filenameUrl, accountId)))
                    .body(JSONObject.toJSONString(parameters))
                    .execute().body();
            workOrder = JSONObject.parseObject(data);
            /**存放redis*/
            redisService.add(RedisConstant.WXPAY_KEY_ZFF + orderNO, userId.toString(), 120);
            log.info("创建预授权订单返回值:   " + workOrder);
            return workOrder.getString("apply_permissions_token");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            log.info("创建预授权订单异常", e);
            return null;
        }
    }

    @Override
    public void callbackInform(HttpServletRequest request, HttpServletResponse response) {
        JSONObject parameters = new JSONObject();
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        JSONObject decrypt;
        try {
            out = response.getWriter();
            ServletInputStream servletInputStream = request.getInputStream();
            byte[] callBackInBytes = IoUtil.readBytes(servletInputStream, request.getContentLength());
            String callBackIn = new String(callBackInBytes, "utf-8");
            log.info("支付分返回结果： " + callBackIn);
            //反序列化
            WxPay wxPay = JSON.parseObject(callBackIn, WxPay.class);
            log.info("反序列化： " + wxPay);

            String verifier = request.getHeader("Wechatpay-Serial");
            String signature = request.getHeader("Wechatpay-Signature");
            String timestamp = request.getHeader("Wechatpay-Timestamp");
            String nonce = request.getHeader("Wechatpay-Nonce");
            log.info("Wechatpay-Serial：{},{},{},{} " ,verifier,signature,timestamp,nonce);
            WeixinConfig weixinPayConfig = weixinPayConfigService.getByVerifier(verifier);
            if (weixinPayConfig == null) {
                log.info("读取微信证书失败");
                parameters.put("code", "ERROR_NAME");
                parameters.put("message", "读取失败");
                throw new BaseException("500", "解密失败");
            }
            String value = weixinPayConfig.getApiv3Key();
            //得到密钥
            AesUtil aesUtil = new AesUtil((value.getBytes(StandardCharsets.UTF_8)));
            //log.info("得到密钥： "+aesUtil.toString());
            //解密
            String decryptToString = aesUtil.decryptToString(
                    wxPay.getResource().getAssociated_data().getBytes(),
                    wxPay.getResource().getNonce().getBytes("UTF-8"),
                    wxPay.getResource().getCiphertext());
            decrypt = JSONObject.parseObject(decryptToString);
            log.info("微信支付分回调结果通知={}",decrypt.toJSONString());
            String orderNO = null;
            String refund_no = null;
            String out_trade_no = null;
            String transactionId = null;
            String refundMoney = null; // payer_refund 退款给用户的金额，不包含所有优惠券金额 ; refund 退款金额，币种的最小单位，只能为整数，不能超过原订单支付金额，如果有使用券，后台会按比例退
            String fee_amt = null;
            RefundOrder refundOrder = null;
            Date createtime = DateUtil.parse(wxPay.getCreate_time());
            switch (wxPay.getEvent_type()) {
                case "PAYSCORE.USER_OPEN_SERVICE":   //授权
                    check(decrypt, RechargeConstant.WXZFF_AUTH, parameters, createtime);
                    log.info("授权成功，用户标识为：" + decrypt.get("openid"));
                    break;
                case "PAYSCORE.USER_CLOSE_SERVICE": //解除授权
                    check(decrypt, RechargeConstant.WXZFF_NOT_AUTH, parameters, createtime);
                    log.info("解除授权成功，用户标识为：" + decrypt.get("openid"));
                    break;
                case "PAYSCORE.USER_CONFIRM":   //确认订单
                    log.info("确认订单,回调参数=" + decrypt);
                    orderNO = decrypt.get("out_order_no").toString();
                    finishRecharge(orderNO, null, RechargeConstant.recharge_comfirm, true, null, null, null);
                    break;
                case "PAYSCORE.USER_PAID":      //支付成功
                    log.info("支付成功" + decrypt.toJSONString());
                    orderNO = decrypt.get("out_order_no").toString();
                    Integer total_amount = decrypt.getInteger("total_amount");
                    String transaction_id = null;
                    String endTime = decrypt.getJSONObject("time_range").getString("end_time");
                    JSONObject collection = decrypt.getJSONObject("collection");
                    if (collection != null && !collection.isEmpty()) {
                        JSONArray details = collection.getJSONArray("details");
                        if (details != null && !details.isEmpty()) {
                            transaction_id = details.getJSONObject(0).getString("transaction_id");
                            endTime = details.getJSONObject(0).getString("paid_time");
                        }
                    }

                    finishRecharge(orderNO, total_amount, RechargeConstant.recharge_success, true, null, transaction_id, endTime);
                    break;
                    //退款成功通知
                case "REFUND.SUCCESS":
                    //文档地址  https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter6_1_28.shtml
                    refund_no = decrypt.get("out_refund_no").toString(); // 商户退款单号
                    out_trade_no = decrypt.get("out_trade_no").toString(); // 返回的商户订单号
                    transactionId = decrypt.get("transaction_id").toString(); // 微信支付订单号
                    refundMoney = decrypt.getJSONObject("amount").getString("payer_refund"); // payer_refund 退款给用户的金额，不包含所有优惠券金额 ; refund 退款金额，币种的最小单位，只能为整数，不能超过原订单支付金额，如果有使用券，后台会按比例退

                    if (!redisService.setNx(RedisConstant.REFUND_LOCK + "callback" +refund_no, RedisConstant.REFUND_LOCK, 60)) {
                        log.warn("获取分布式锁失败{}",refund_no);
                    }
                    try{
                        refundOrder = refundOrderDao.getByRefundNO(refund_no);
                        if (Objects.isNull(refundOrder)){
                            log.error("回调时获取退款订单表为空，排查执行退款时的退款订单表插入动作问题，退款单号={}",refund_no);
                        }
                        // 微信支付分退款回调成功，更新refundorder，发送MQ消息
                        if (Objects.nonNull(refundOrder)){
                            // 发送MQ消息
                            PayCallbackData msgData = new PayCallbackData();
//                            String msgId = String.format("%s_%s", RefundConstant.ADAPAY_ZFB, StringUtil.getRandomString(8));
//                            msgData.setMsgId(msgId);
//                msgData.setFeedback("feedback");
                            CallbackDataVo callbackDataVo = new CallbackDataVo();
                            callbackDataVo.setPaymentId(transactionId);  //第三方支付id 微信支付订单号
                            callbackDataVo.setType(2);  // 类型 1 支付 ， 2 退款
                            callbackDataVo.setStatus("SUCCESS");
                            callbackDataVo.setOrderNo(refund_no); // 单号（订单号 退单号）
//                            callbackDataVo.setTotalRefundMoney(String.valueOf(totalRefundMoney));
                            callbackDataVo.setRefundMoney(refundMoney); // 退款金额
                            callbackDataVo.setConfirmTime(DateTimeUtil.getNowTime());   // 支付时间  退款时间
                            callbackDataVo.setTransactionId(out_trade_no);  // 返回的商户订单号
                            callbackDataVo.setFee_amt(fee_amt);
                            msgData.setData(callbackDataVo);
                            // 记录MQ消息内容
//                            refundOrder.setMessageId(msgId);
                            refundOrder.setMessageContent(JSON.toJSONString(msgData));
                            refundOrder.setRouteKey(RabbitMQData.orderkey);
                            refundOrder.setExchange(RabbitMQData.orderexchange);
                            // 设置消息消费状态为未消费
                            refundOrder.setMsgSuccess(false);

                            // 修改订单退款状态为成功
                            refundOrder.setRefundStatus(RefundConstant.REFUND_SUCCESS);
                            // 跟新退款订单状态
                            refundOrderDao.updateCallBackInfo(refundOrder);
                            log.info("发送MQ消息{}",JSON.toJSONString(msgData));
                            mqProducer.sendToRide(RabbitMQData.orderexchange,RabbitMQData.orderkey,JSON.toJSONString(msgData));
                        }
                    }catch (Exception e){
                        log.error("退款异步回调发生异常",e);
                        // 防止外层异常捕获被吞
                        throw new Exception(e);
                    } finally {
                        redisService.del(RedisConstant.REFUND_LOCK + refund_no);
                    }

                    break;
                    // 退款异常通知
                case "REFUND.ABNORMAL":
                    if (!redisService.setNx(RedisConstant.REFUND_LOCK + "callback" + refund_no, RedisConstant.REFUND_LOCK, 60)) {
                        log.warn("获取分布式锁失败{}",refund_no);
                    }
                    try{
                        refundOrder = refundOrderDao.getByRefundNO(refund_no);
                        if (Objects.isNull(refundOrder)){
                            log.error("回调时获取退款订单表为空，排查执行退款时的退款订单表插入动作问题，退款单号={}",refund_no);
                        }
                        // 更新refundorder
                        if (Objects.nonNull(refundOrder)){
                            refundOrder.setRefundStatus(RefundConstant.REFUND_FAIL);
                            refundOrderDao.update(refundOrder);
                        }
                    }catch (Exception e){
                        log.error("退款异步回调发生异常",e);
                        // 防止外层异常捕获被吞
                        throw new Exception(e);
                    } finally {
                        redisService.del(RedisConstant.REFUND_LOCK + refund_no);
                    }

                    break;
                    // 退款关闭通知
                case "REFUND.CLOSED":
                    if (!redisService.setNx(RedisConstant.REFUND_LOCK + "callback" + refund_no, RedisConstant.REFUND_LOCK, 60)) {
                        log.warn("获取分布式锁失败{}",refund_no);
                    }
                    try{
                        refundOrder = refundOrderDao.getByRefundNO(refund_no);
                        if (Objects.isNull(refundOrder)){
                            log.error("回调时获取退款订单表为空，排查执行退款时的退款订单表插入动作问题，退款单号={}",refund_no);
                        }
                        // 更新refundorder
                        if (Objects.nonNull(refundOrder)){
                            refundOrder.setRefundStatus(RefundConstant.REFUND_FAIL);
                            refundOrderDao.update(refundOrder);
                        }
                    }catch (Exception e){
                        log.error("退款异步回调发生异常",e);
                        // 防止外层异常捕获被吞
                        throw new Exception(e);
                    } finally {
                        redisService.del(RedisConstant.REFUND_LOCK + refund_no);
                    }

                    break;
            }
            //返回消息
            parameters.put("code", "SUCCESS");
        } catch (Exception e) {
            log.error("支付分回调异常", e);
            parameters.put("code", "ERROR_NAME");
            parameters.put("message", "读取失败");
            throw new BaseException("500", "读取失败");
        } finally {
            out.write(parameters.toJSONString());
            out.flush();
            out.close();
        }
    }


    @Override
    public Boolean wakeUpPaymentPoints(Integer accountId, Integer userId, Integer money, String openid, Integer adAccountId
            , AdAccountFee adAccountFee) {
        String orderNO = "WXZFF" + DateTimeUtil.getDaformatyyyyMMddHHmmss(new Date()) + TenpayUtil
                .buildRandom(6);

        WeixinConfig weixinConfig = weixinConfigDao.getByAccountId(accountId);
        if (weixinConfig == null) {
            throw new BaseException("-2006", "该品牌微信支付未配置");
        }
        User user = userService.getByUserId(userId);
        MpBrandConfig mpBrandConfig = mpBrandConfigService.getByAccountId(user.getAccountId());
        String data = order_base(weixinConfig, userId, accountId, false, money, openid, orderNO, user.getPhone(), adAccountId
                , adAccountFee, mpBrandConfig.getName());
        if (data == null) {
            return false;
        }
        return true;
    }

    @Override
    public String create_zff_order(Integer accountId, User user) {
        SortedMap<Object, Object> map = new TreeMap<Object, Object>();

        WeixinConfig weixinConfig = weixinConfigDao.getByAccountId(user.getAccountId());
        if (weixinConfig == null) {
            throw new BaseException("-2006", "该品牌微信支付未配置");
        }
        AdAccountFee adAccountFee = adAccountFeeService.getByAccountId(accountId, null);
        if (adAccountFee == null) {
            throw new BaseException("-3056", "计费规则未配置");
        }
        /**查询有没有为完结的支付分订单*/
        Recharge recharge = rechargeService.getByWxzzfNotPay(user.getUserId(), RechargeConstant.RECHARGE_WEIXIN_AFF);
        /**5分钟内存在订单，直接返回成功*/
        if (recharge != null) {
            throw new BaseException("-170001", "您有一笔订单支付失败，请先支付再用车");
        }
        /*String orderNO = "WXZFF" + DateTimeUtil.getDaformatyyyyMMddHHmmss(new Date()) + TenpayUtil
                .buildRandom(6);*/
        String orderNO = OrderNoUtil.getOrderNO((long) TenpayUtil.buildRandom(6), RechargeConstant.recharge_zff);
        MpBrandConfig mpBrandConfig = mpBrandConfigService.getByAccountId(user.getAccountId());

        String data = order_base(weixinConfig, user.getUserId(), user.getAccountId(), true,
                adAccountFee.getAreaMoney(), null, orderNO, user.getPhone(), accountId, adAccountFee, mpBrandConfig.getName());
        if (data == null) {
            throw new BaseException("-101", "系统异常");
        }
        JSONObject jsonObject = JSON.parseObject(data);
        String msg = jsonObject.getString("package");
        String mchid = jsonObject.getString("mchid");
        // 随机字符串
        String nonce_str = WeixinPayUtil.getNonceStr(false);
        String timestamp = Sha1Util.getTimeStamp();

        map.put("mch_id", mchid);
        map.put("package", msg);
        map.put("nonce_str", nonce_str);
        map.put("timestamp", timestamp);
        map.put("sign_type", "HMAC-SHA256");
        String sign = HMACSHA256.sha256_HMAC(map, weixinConfig.getApiv3Key()).toUpperCase();
        map.put("sign", sign);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("mch_id", mchid);
        jsonObject1.put("timeStamp", timestamp);
        jsonObject1.put("nonce_str", nonce_str);
        jsonObject1.put("package", msg);
        jsonObject1.put("sign_type", "HMAC-SHA256");
        jsonObject1.put("sign", sign);
        jsonObject1.put("orderNO",orderNO);
        return jsonObject1.toJSONString();
    }

    @Override
    public Boolean getOrderState(String orderNO) {
        Recharge recharge=rechargeService.getByOrderNO(orderNO);
        if(recharge==null){
            return false;
        }
        if(Objects.equals(recharge.getState(), RechargeConstant.recharge_comfirm)){
            return true;
        }
        return false;
    }

    /**
     * 支付分订单构建
     *
     * @param weixinConfig 微信配置
     * @param userId       用户id
     * @param accountId    品牌id
     * @param checked      是否是需确认模式
     * @param money        金额
     * @param openid       openid
     * @param orderNO      订单编号
     * @return
     */
    public String order_base(WeixinConfig weixinConfig, Integer userId, Integer accountId, boolean checked
            , Integer money, String openid, String orderNO, String phone, Integer adAccountId, AdAccountFee adAccountFee, String name) {

        WeixinPayConfig weixinPayConfig = weixinPayConfigService.getByAccountId(accountId, 2);
        if (weixinPayConfig == null) {
            throw new BaseException("-2006", "该品牌微信支付未配置");
        }

        /***需确认实现方式*/
        JSONObject parameters = new JSONObject();
        parameters.put("out_order_no", orderNO);    //商户服务订单号
        parameters.put("appid", weixinPayConfig.getAppId());//公众账号ID
        parameters.put("service_id", weixinConfig.getServiceId());//服务ID
        parameters.put("service_introduction", "骑行收费");//服务信息
        JSONObject timeRange = new JSONObject();
        timeRange.put("start_time", "OnAccept");//服务开始时间
        parameters.put("time_range", timeRange);//服务时间段
        JSONObject riskFund = new JSONObject();
        riskFund.put("name", "ESTIMATE_ORDER_COST");//风险金名称
        riskFund.put("amount", money); //风险金额
        parameters.put("risk_fund", riskFund); //订单风险金
        parameters.put("notify_url", weixinConfig.getCallbackURL()); //商户回调地址
        if (!checked) {
            parameters.put("openid", openid);             //用户标识      免确认订单：必填，需确认订单：不填
            parameters.put("need_user_confirm", false);                 //是否需要用户确认
        }
        /**计费规则*/
        JSONArray post_payments = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "计费规则");
        jsonObject.put("description", "骑行费用" + adAccountFee.getBaseTimeFee().doubleValue()/100 + "元/" + adAccountFee.getBaseTime() + "分钟，详情见" + name + "小程序");
        post_payments.add(jsonObject);
        parameters.put("post_payments", post_payments);
        log.info("创建支付分订单，请求参数" + parameters.toString());
        JSONObject workOrder;
        String data;
        try {
            data = HttpRequest.post(WeixinConstant.establishOrderUrl)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.ACCEPT, "application/json")
                    // 签名
                    .header("Authorization", "WECHATPAY2-SHA256-RSA2048" + " "
                            + PayScore
                            .getToken("POST", WeixinConstant.establishOrderUrl, JSONObject.toJSONString(parameters), weixinPayConfig.getPartner(), weixinConfig.getCertSerNo(), String.format(
                                    WeixinConstant.filenameUrl, accountId)))
                    .body(JSONObject.toJSONString(parameters))
                    .execute().body();
            workOrder = JSONObject.parseObject(data);
            log.info("创建支付分订单返回值:   " + workOrder);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            log.info("创建订单异常", e);
            return null;
        }
        if (!WeixinConstant.WEIXIN_ZFF_CREATED.equals(workOrder.getString("state")) && !WeixinConstant.WEIXIN_ZFF_DOING.equals(workOrder.getString("state"))) {
            log.error("存在未完成订单=" + workOrder);
            return null;
        }
        Recharge recharge = new Recharge();
        recharge.setRechargeType(RechargeConstant.recharge_zff);
        recharge.setType(RechargeConstant.RECHARGE_WEIXIN_AFF);
        recharge.setOrderNO(orderNO);
        recharge.setRechargeTime(DateTimeUtil.getNowTime());
        recharge.setUserId(userId);
        recharge.setState(RechargeConstant.recharge_notcheck);
        if (!checked) {
            recharge.setState(RechargeConstant.recharge_comfirm);
        }
        recharge.setAdAccountId(adAccountId);
        recharge.setBrandId(accountId);
        recharge.setMoney(money.doubleValue());
        recharge.setRemark("支付分订单创建");
        recharge.setDeposit(false);
        recharge.setPhone(phone);
        rechargeService.insert(recharge);
        return data;
    }


    @Override
    public Boolean finishOrder(PayPoints payPoints, Integer accountId, String serNO,
                               AdAccountFee adAccountFee, String name, String time) {
        WeixinConfig weixinConfig = weixinConfigDao.getByAccountId(accountId);
        if (weixinConfig == null) {
            throw new BaseException("-2006", "该品牌微信支付未配置");
        }

        WeixinPayConfig weixinPayConfig = weixinPayConfigService.getByAccountId(accountId, 2);
        if (weixinPayConfig == null) {
            throw new BaseException("-2006", "该品牌微信支付未配置");
        }

        JSONObject parameters = new JSONObject();
        parameters.put("appid", weixinPayConfig.getAppId());
        parameters.put("service_id", weixinConfig.getServiceId());
        List<JSONObject> postPaymentsList = new ArrayList<>();
        /**计费规则*/
        JSONObject fee = new JSONObject();
        fee.put("name", "计费规则");
        fee.put("description", "骑行费用" + ((double)  adAccountFee.getBaseTimeFee() / 100 + "元/" +adAccountFee.getBaseTime()) + "分钟，详情见" + name + "小程序");
        postPaymentsList.add(fee);
        JSONObject rideTime = new JSONObject();
        rideTime.put("name", "骑行时长");
        rideTime.put("description", time);
        postPaymentsList.add(rideTime);

        JSONObject postPayments = new JSONObject();
        postPayments.put("name", "骑行费用");
        postPayments.put("amount", payPoints.getAmount());
        postPaymentsList.add(postPayments);
        /*if (payPoints.getDispatchMoney() != null) {
            JSONObject dispatchMoney = new JSONObject();
            dispatchMoney.put("name", "调度费用");
            dispatchMoney.put("amount", payPoints.getDispatchMoney());
            postPaymentsList.add(dispatchMoney);
        }*/

        parameters.put("post_payments", postPaymentsList);
        parameters.put("total_amount", payPoints.getTotal_amount());
        JSONObject timeRange = new JSONObject();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime t = LocalDateTime.now();
        timeRange.put("end_time", t.format(formatter));
        parameters.put("time_range", timeRange);

        parameters.put("notify_url", weixinConfig.getCallbackURL());
        JSONObject jsonObject;
        String createOrderUrl = WeixinConstant.establishOrderUrl + "/" + payPoints.getOut_order_no() + "/complete";
        try {
            log.info("完结支付分订单，请求参数:    " + parameters);
            String data = HttpRequest.post(createOrderUrl)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.ACCEPT, "application/json")
                    .header("Authorization", "WECHATPAY2-SHA256-RSA2048" + " "
                            + PayScore
                            .getToken("POST", createOrderUrl, JSONObject.toJSONString(parameters), weixinPayConfig.getPartner(), weixinConfig.getCertSerNo(), String.format(
                                    WeixinConstant.filenameUrl, accountId)))
                    .body(JSONObject.toJSONString(parameters))
                    .execute().body();
            jsonObject = JSONObject.parseObject(data);
            log.info("完结支付分订单，返回参数:    " + jsonObject);
        } catch (Exception e) {
            return false;
        }
        if (!StringUtils.isEmpty(jsonObject.getString("code"))) {
            return false;
        }
        switch (jsonObject.getString("state")) {
            case "CREATED":
                log.info("订单未进行");
                return false;
            case "DOING":
                //finish(jsonObject);
                return true;
            case "DONE":
                //finish(jsonObject);
                return true;
            case "REVOKED":
                log.info("订单已取消");
                return false;
            case "EXPIRED":
                log.info("订单已失效");
                return false;
            default:
                log.info("网络异常");
                return false;
        }
    }

    /**
     * 支付分订单完结
     *
     * @param jsonObject
     */
    public void finish(JSONObject jsonObject) {
        String orderNO = jsonObject.get("out_order_no").toString();
        Integer total_amount = jsonObject.getInteger("total_amount");
        String transaction_id = null;
        JSONObject collection = jsonObject.getJSONObject("collection");
        if (collection != null && collection.size() > 0) {
            JSONArray details = collection.getJSONArray("details");
            if (details != null && details.size() > 0) {
                transaction_id = details.getJSONObject(0).getString("transaction_id");
            }
        }
        String endTime = jsonObject.getJSONObject("time_range").getString("end_time");
        finishRecharge(orderNO, total_amount, RechargeConstant.recharge_success, true, null, transaction_id, endTime);
    }

    @Override
    public Boolean finishOrderOutTime(Integer userId, Integer money) {
        User user = userService.getByUserId(userId);
        if (user == null) {
            return false;
        }
        Recharge recharge = rechargeService.getByWxzzfNotPay(userId, RechargeConstant.RECHARGE_WEIXIN_AFF);
        if (recharge == null) {
            return false;
        }
        AdAccountFee adAccountFee = adAccountFeeService.getByAccountId(recharge.getAdAccountId(), null);
        MpBrandConfig mpBrandConfig = mpBrandConfigService.getByAccountId(user.getAccountId());
        String serNO = UUID.randomUUID().toString();
        PayPoints payPoints = new PayPoints();
        payPoints.setAmount(money);
        payPoints.setName("自动结束订单扣费");
        payPoints.setTotal_amount(money);
        payPoints.setOut_order_no(recharge.getOrderNO());
        Boolean result = finishOrder(payPoints, user.getAccountId(), serNO, adAccountFee, mpBrandConfig.getName(), "1分钟");
        return result;
    }


    /**
     * 获取openid
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenid(String code, String appId, String appSecret) {
        // 查询openid
        Map<String, Object> map = new HashMap<>();
        map.put("url", "https://api.weixin.qq.com/sns/jscode2session");
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String urlJoint = HttpUrlUtil.urlJoint(map);
        //log.info("获取openid请求地址: " + urlJoint);
        JSONObject jsonObject;
        try {
            String data = HttpRequest.get(urlJoint)
                    .body("")
                    .execute().body();
            jsonObject = JSONObject.parseObject(data);
            // log.info("获取openid 返回参数:    " + jsonObject);
            return (String) jsonObject.get("openid");
        } catch (Exception e) {
            throw new BaseException("-170003", "获取openId失败");
        }
    }

    @Override
    public Boolean get_zff_status(User user) {
        UserWxzff userWxzff = userWxzffService.getByUserId(user.getUserId());
        if (userWxzff == null) {
            return false;
        }
        WeixinPayConfig weixinPayConfig = weixinPayConfigService.getByAccountId(user.getAccountId(), 2);
        if (weixinPayConfig == null) {
            throw new BaseException("-2006", "该品牌微信支付未配置");
        }
        WeixinConfig weixinConfig = weixinConfigDao.getByAccountId(user.getAccountId());
        if (weixinConfig == null) {
            throw new BaseException("-2006", "该品牌微信支付未配置");
        }
        User userDB = userService.getByUserId(user.getUserId());
        Map<String, Object> map = new HashMap<>();
        map.put("url", "https://api.mch.weixin.qq.com/v3/payscore/user-service-state");
        map.put("appid", weixinPayConfig.getAppId());
        map.put("service_id", weixinConfig.getServiceId());
        map.put("openid", userWxzff.getOpenId());
        String createOrderUrl = HttpUrlUtil.urlJoint(map);
        //log.info("获取openid请求地址: " + urlJoint);
        JSONObject jsonObject;
        try {
            // String createOrderUrl="https://api.mch.weixin.qq.com/v3/payscore/user-service-state?service_id=00003001000000164551365497316745&appid=wx1c1d83ba40dd9e00&openid=oveon466Yf9Fw7lFTHqO6b70Xack";
            String data = HttpRequest.get(createOrderUrl)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .header(Header.ACCEPT, "application/json")
                    .header("Authorization", "WECHATPAY2-SHA256-RSA2048" + " "
                            + PayScore
                            .getToken("GET", createOrderUrl, "", weixinPayConfig.getPartner(), weixinConfig.getCertSerNo(), String.format(
                                    WeixinConstant.filenameUrl, weixinConfig.getAccountId())))
                    .execute().body();
            jsonObject = JSONObject.parseObject(data);
            // log.info("获取openid 返回参数:    " + jsonObject);
            String tmp = jsonObject.getString("use_service_state");
            log.info("use_service_state返回参数:    " + jsonObject);
            if (tmp.equals("AVAILABLE")) {
                userService.updateDeposit(user.getUserId(), DepositStateConstant.DEPOSIT_STATE_SCORE);
            } else {
                /**只有授权支付分的用户才触发清除支付分免押状态*/
                if (userDB != null && userDB.getDepositState().equals(DepositStateConstant.DEPOSIT_STATE_SCORE)) {
                    userService.updateDeposit(user.getUserId(), DepositStateConstant.DEPOSIT_STATE_NOTPAY);
                }
            }
            return tmp.equals("AVAILABLE");
        } catch (Exception e) {
            throw new BaseException("-170003", "获取用户状态失败");
        }
    }


    /**
     * 数据入库
     *
     * @param decrypt
     * @param state
     */
    private void check(JSONObject decrypt, Integer state, JSONObject parameters, Date createTime) {
        String openId = decrypt.getString("openid");
        String orderNO = decrypt.getString("authorization_code");
        String service_id = decrypt.getString("service_id");
        WeixinConfig weixinConfig = weixinConfigDao.getByServiceId(service_id);
        if (weixinConfig == null) {
            log.info("获取service_id失败,openid=" + openId + "service_id=" + service_id);
            parameters.put("code", "ERROR_NAME");
            parameters.put("message", "超时");
            return;
        }
        Integer userId = null;
        /**修改用户押金状态*/
        if (state.equals(RechargeConstant.WXZFF_NOT_AUTH)) {
            List<UserWxzff> userWxzffs = userWxzffService.getByOpenId(openId, weixinConfig.getAccountId());
            if (!userWxzffs.isEmpty()) {
                for (UserWxzff userWxzfDB : userWxzffs) {
                    userId = userWxzfDB.getUserId();
                    User user = userService.getByUserId(userWxzfDB.getUserId());
                    Integer depositState = DepositStateConstant.DEPOSIT_STATE_NOTPAY;
                    if (user.getDepositMoney() > 0) {
                        depositState = DepositStateConstant.DEPOSIT_STATE_PAY;
                    }
                    userService.updateDeposit(userWxzfDB.getUserId(), depositState);
                }
            } else {
                log.info("获取userId失败,openid=" + openId);
                parameters.put("code", "ERROR_NAME");
                parameters.put("message", "超时");
                return;
            }
        } else {
            String id = redisService.get(RedisConstant.WXPAY_KEY_ZFF + orderNO);
            if (id == null) {
                log.info("获取userId失败,openid=" + openId);
                parameters.put("code", "ERROR_NAME");
                parameters.put("message", "超时");
                return;
            }
            userId = Integer.valueOf(id);
            User user = userService.getByUserId(userId);
            if (user != null) {
                /**查询如果正在骑行，需创建支付分订单*/
                MachineBorrow machineBorrow = machineBorrowDao.getByUserId(userId);
                if (machineBorrow != null) {
                    Machine machine = machineService.getByMachineId(machineBorrow.getMachineId());
                    AdAccountFee adAccountFee = adAccountFeeService.getByAccountId(machine.getAccountId(), machine.getMachineId());
                    wakeUpPaymentPoints(user.getAccountId(), user.getUserId(), 10000, openId, machine.getAccountId(), adAccountFee);
                }
                userService.updateDeposit(userId, DepositStateConstant.DEPOSIT_STATE_SCORE);
            }
        }

        UserWxzff userWxzff = new UserWxzff();
        userWxzff.setOpenId(openId);
        userWxzff.setAccountId(weixinConfig.getAccountId());
        userWxzff.setUserId(userId);
        userWxzff.setUpdateTime(createTime);
        userWxzff.setState(state);
        if (state.equals(RechargeConstant.WXZFF_NOT_AUTH)) {
            userWxzff.setRemark("用户取消授权");
        } else {
            userWxzff.setRemark("用户授权");
        }
        userWxzffService.add(userWxzff);


    }

    /**
     * 完结订单
     *
     * @param orderNO
     */
    @Transactional
    public void finishRecharge(String orderNO, Integer totalMoney, Integer state, Boolean isPay, String serNO, String transaction_id, String endTime) {
        try {
            Recharge recharge = rechargeService.getByOrderNO(orderNO);
            if (recharge != null) {
                Recharge rechargeUp = new Recharge();
                rechargeUp.setOrderNO(recharge.getOrderNO());
                rechargeUp.setState(state);
                /**备注放入微信支付分订单号*/
                if (transaction_id != null) {
                    rechargeUp.setRemark(transaction_id);
                }
                String details ="";
                User user = userService.getByUserId(recharge.getUserId());
                if (state.equals(RechargeConstant.recharge_success)) {
                    if (isPay&&totalMoney>0) {
                        userService.updateMoney(recharge.getUserId(), totalMoney.doubleValue());
                        /** 添加金额变动日志 */
                        UserAccountLog userAccountLog = new UserAccountLog();
                        userAccountLog.setAccountId(user.getAccountId());
                        userAccountLog.setUserId(recharge.getUserId());
                        userAccountLog.setOperaTime(DateTimeUtil.getNowTime());
                        if (endTime != null) {
                            userAccountLog.setOperaTime(StringUtil.parseTime(endTime));
                        }
                        userAccountLog.setMoney(totalMoney.doubleValue());
                        userAccountLog.setMoneyType(0);
                        userAccountLog.setType(1);
                        userAccountLog.setRemark("支付分订单充值");
                        userAccountLogService.insert(userAccountLog);
                        recharge.setMoney(totalMoney.doubleValue());
                        //记录新表流水(需要展示微信支付分订单号)
                        weixinPayService.addTransationLog(user, recharge, transaction_id == null ? orderNO : transaction_id, StringUtil.parseTime(endTime), PayPlatformContent.WeChat, TransationLogConstant.BUSINESS_BALANCE_CYCLING
                                ,transaction_id);
                        weixinPayService.addUserCapitalChange(user, recharge, PayPlatformContent.PAY_RIDELOG_PAY,
                                BusinessConstant.BUSINESS_BALANCE_CYCLING, StringUtil.parseTime(endTime), details, transaction_id, user.getAccountId(),
                                0L, totalMoney.longValue(), 0L, PayPlatformContent.PAY_RECHARGE);

                    }
                    rechargeUp.setPayTime(DateTimeUtil.getNowTime());
                    if (endTime != null) {
                        rechargeUp.setPayTime(StringUtil.parseTime(endTime));
                    }
                    rechargeUp.setMoney(totalMoney.doubleValue());
                    /***查询借车记录*/
                    MachineBorrow machineBorrow = machineBorrowDao.getByUserId(recharge.getUserId());
                    if (machineBorrow != null) {
                        RideLog rideLog = rideLogService.getByOrderNO(machineBorrow.getOrderNO());
                        if (rideLog != null) {
                            if (serNO == null) {
                                serNO = redisService.get(RedisConstant.USER_FINISH_PAY + machineBorrow.getUserId());
                            }
                            String brtInfo = redisService.get(serNO);
                            if (brtInfo != null) {
                                details=rideLog.getOrderNO();
                                /**处理扣费逻辑*/
                                BorrowReturnTer info = JSONObject.parseObject(brtInfo, BorrowReturnTer.class);
                                info.setMerchantNO(recharge.getOrderNO());
                                info.setPayTime(StringUtil.parseTime(endTime));
                                info.setPayMoney(totalMoney.doubleValue());
                                //人工结束订单使用支付分支付是不存在欠款金额
                                info.setLessMoney(0);
                                machineService.handlePay(info);
                                //machineService.ter_lock(serNO);
                                Machine machine = machineService.getByMachineId(machineBorrow.getMachineId());
                                /**给终端下发指令*/
                                String serNO1 = UUID.randomUUID().toString();
                                terControlService.sendControl(serNO1, rideLog.getMachineNO(), ControlTypeConstant.CONTROL_TYPE_CONTROL, ControlTypeConstant.CONTROL_TYPE_LOCK, "", machine, true, -1, null, null);
                                /**记录日志信息 */
                                OrderLog orderLog = new OrderLog();
                                orderLog.setOrderSerNo(serNO1);
                                orderLog.setMachineId(rideLog.getMachineId());
                                orderLog.setMachineNo(rideLog.getMachineNO());
                                orderLog.setUserCode(rideLog.getUserCode());
                                orderLog.setChannelType(Integer.valueOf(ControlWay.CLIENT_GPRS.getCode()));
                                orderLog.setBusinessType(OrderLogTypeConstant.BUSINESSTYPE_RETURN);
                                orderLog.setOpTime(DateTimeUtil.getNowTime());
                                orderLog.setOpType(OrderLogTypeConstant.OPTYPE_USER);
                                orderLog.setOrderContent(ControlTypeConstant.CONTROL_TYPE_LOCK);
                                orderLog.setOrderSource(-1);
                                orderLog.setOrderType(ControlTypeConstant.CONTROL_TYPE_CONTROL);
                                orderLog.setOpId(rideLog.getUserId());
                                orderLog.setRemark("用户还车" + ("[GPRS]"));
                                orderLog.setAccountUserId(rideLog.getAccountId());
                                orderLogDao.insert(orderLog);
                                log.info("订单编号=" + machineBorrow.getOrderNO() + "还车下发指令");
                                //添加记录
                                adaPayService.addRideFeeLog(machineBorrow.getOrderNO(), rideLog.getAccountId(), user, totalMoney, 0,
                                        RechargeConstant.recharge_zff);
                            } else {
                                log.warn("支付分支付未找到订单" + machineBorrow.getOrderNO());
                            }

                        }
                    }
                }

                if (isPay) {
                    rechargeService.editWizffPay(rechargeUp);
                }

            }else{
                log.info("{}订单未查到数据", orderNO);
            }
        } catch (Exception e) {
            log.error("订单{}完结订单失败",orderNO, e);
        }
    }


    @Override
    public Boolean cancelOrder(User user, String remark) {
        WeixinPayConfig weixinPayConfig = weixinPayConfigService.getByAccountId(user.getAccountId(), 2);
        if (weixinPayConfig == null) {
            return false;
        }
        WeixinConfig weixinConfig = weixinConfigDao.getByAccountId(user.getAccountId());
        if (weixinConfig == null) {
            return false;
        }
        Recharge recharge = rechargeService
                .getByWxzzfNotPay(user.getUserId(), RechargeConstant.RECHARGE_WEIXIN_AFF);
        if (recharge != null) {
            String createOrderUrl = "https://api.mch.weixin.qq.com/v3/payscore/serviceorder/" + recharge.getOrderNO()
                    + "/cancel";
            //log.info("获取openid请求地址: " + urlJoint);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("appid", weixinPayConfig.getAppId());
            jsonObject.put("service_id", weixinConfig.getServiceId());
            jsonObject.put("reason", remark);
            try {
                String data = HttpRequest.post(createOrderUrl)
                        .header(Header.CONTENT_TYPE, "application/json")
                        .header(Header.ACCEPT, "application/json")
                        .header("Authorization", "WECHATPAY2-SHA256-RSA2048" + " "
                                + PayScore.getToken("POST", createOrderUrl, JSONObject.toJSONString(jsonObject), weixinPayConfig.getPartner(), weixinConfig.getCertSerNo(), String.format(
                                WeixinConstant.filenameUrl, user.getAccountId())))
                        .body(JSONObject.toJSONString(jsonObject))
                        .execute().body();
                log.info("取消订单返回参数=" + data);
                JSONObject result = JSON.parseObject(data);
                if (result == null || result.getString("code") != null) {
                    return false;
                } else {
                    Recharge rechargeDB = new Recharge();
                    rechargeDB.setOrderNO(recharge.getOrderNO());
                    rechargeDB.setMoney(0D);
                    rechargeDB.setState(RechargeConstant.recharge_cancelOrder);
                    rechargeService.editWizffPay(rechargeDB);
                }
            } catch (Exception e) {
                log.error("取消支付分订单失败", e);
                return false;
            }
        }
        return true;
    }

    @Override
    public Boolean refund(String orderNO, String reason, Integer refundMoney, User user, String refundNo) {
        // https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter6_1_26.shtml
        WeixinPayConfig weixinPayConfig = weixinPayConfigService.getByAccountId(user.getAccountId(), 2);
        if (weixinPayConfig == null) {
            throw new BaseException("-2006", "该品牌微信支付未配置");
        }
        WeixinConfig weixinConfig = weixinConfigDao.getByAccountId(user.getAccountId());
        if (weixinConfig == null) {
            throw new BaseException("-2006", "该品牌微信支付未配置");
        }
        Recharge recharge = rechargeService.getByOrderNO(orderNO);
        if (recharge != null && recharge.getType().equals(RechargeConstant.RECHARGE_WEIXIN_AFF)) {
            String url = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds";
            JSONObject parameters = new JSONObject();
            parameters.put("transaction_id", recharge.getRemark());
            parameters.put("out_refund_no", refundNo);
            parameters.put("reason", reason);
            parameters.put("notify_url", weixinConfig.getCallbackURL());
            JSONObject amount = new JSONObject();
            amount.put("refund", refundMoney);
            amount.put("total", recharge.getMoney().intValue());
            amount.put("currency", "CNY");
            parameters.put("amount", amount);
            //log.info("获取openid请求地址: " + urlJoint);
            JSONObject jsonObject;
            try {
                String data = HttpRequest.post(url)
                        .header(Header.CONTENT_TYPE, "application/json")
                        .header(Header.ACCEPT, "application/json")
                        .header("Authorization", "WECHATPAY2-SHA256-RSA2048" + " "
                                + PayScore
                                .getToken("POST", url, JSONObject.toJSONString(parameters), weixinPayConfig.getPartner(), weixinConfig.getCertSerNo(), String.format(
                                        WeixinConstant.filenameUrl, user.getAccountId())))
                        .body(JSONObject.toJSONString(parameters))
                        .execute().body();
                jsonObject = JSONObject.parseObject(data);
                log.info("获取openid 返回参数:    " + jsonObject);
                if ("SUCCESS".equalsIgnoreCase(jsonObject.getString("status")) || "PROCESSING".equalsIgnoreCase(jsonObject.getString("status"))) {
                    return true;
                }
            } catch (Exception e) {
                throw new BaseException("-170003", "获取用户状态失败");
            }
        }
        return false;
    }

    @Override
    public Boolean finishOrderOut(User user, Double allMoney, String serNO, Integer adAccountId, String time, Integer diaPatchMoney, String remark) {
        /**是否微信支付分支付*/
        Recharge recharge = rechargeService.getByWxzzfNotPay(user.getUserId(), RechargeConstant.RECHARGE_WEIXIN_AFF);
        if (recharge != null) {
            Double zffMoney = allMoney;
            PayPoints payPoints = new PayPoints();
            if (zffMoney > 0) {
                payPoints.setAmount(zffMoney.intValue());
                payPoints.setName(remark);
                payPoints.setTotal_amount(zffMoney.intValue());
                payPoints.setDispatchMoney(diaPatchMoney);
            } else {
                payPoints.setAmount(0);
                payPoints.setName(remark);
                payPoints.setTotal_amount(0);
            }
            payPoints.setOut_order_no(recharge.getOrderNO());
            AdAccountFee adAccountFee = adAccountFeeService.getByAccountId(adAccountId, null);
            MpBrandConfig mpBrandConfig = mpBrandConfigService.getByAccountId(user.getAccountId());
            /**非完结支付分订单**/
            if (!finishOrder(payPoints, user.getAccountId(), serNO, adAccountFee, mpBrandConfig.getName(), time)) {
                return false;
            }
            return true;
        }
        return false;
    }

}
